﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DSAServer.Models;
using DSAServer.Models.Input;
using DSAServer.Models.Output;
using DSAServer.Utils;

namespace DSAServer.Service
{
    public class ManagerService
    {
        public InvokeResult<int> Login(UserLoginInfo userLoginInfo)
        {
            InvokeResult<int> result = new InvokeResult<int>();
            var password = DbUtils.Main.Sql("select password from sysuser where loginname=@0", userLoginInfo.user).QuerySingle<string>();
            if (string.IsNullOrEmpty(password))
            {
                result.msg = "账号不存在!";
                return result;
            }

            if (MD5Helper.EnCode(userLoginInfo.password).ToLower() != password)
            {
                result.msg = "密码不正确!";
                return result;
            }
            result.data =
                DbUtils.Main.Sql("select id from sysuser where loginname=@0", userLoginInfo.user).QuerySingle<int>();
            result.ok = true;
            return result;
        }

        public InvokeResult ChangePassword(ChgPwdInfo chgPwdInfo)
        {
            InvokeResult result = new InvokeResult();
            if (string.IsNullOrEmpty(chgPwdInfo.newpassword))
            {
                result.msg = "新密码不能为空!";
                return result;
            }
            if (chgPwdInfo.newpassword != chgPwdInfo.newpassword2)
            {
                result.msg = "2次输入的新密码不一致!";
                return result;
            }
            var oldpassword = DbUtils.Main.Sql("select password from sysuser where id=@0", AppContext.Instance.userId).QuerySingle<string>();
            if (oldpassword != MD5Helper.EnCode(chgPwdInfo.oldpassword).ToLower())
            {
                result.msg = "旧密码不正确!";
                return result;
            }
            DbUtils.Main.Sql("update sysuser set password=@0 where id=@1", MD5Helper.EnCode(chgPwdInfo.newpassword).ToLower(),
                             AppContext.Instance.userId).Execute();
            result.ok = true;
            return result;
        }

        public InvokeResult<List<UserInfo>> QueryUser()
        {
            InvokeResult<List<UserInfo>> result = new InvokeResult<List<UserInfo>>();
            result.data = DbUtils.Main.Sql(@"select loginname as username,password from sysuser order by id desc").QueryMany<UserInfo>();
            result.ok = true;
            return result;
        }

        public InvokeResult SaveUser(UserInfo userInfo)
        {
            InvokeResult result = new InvokeResult();
            if (string.IsNullOrEmpty(userInfo.username))
            {
                result.msg = "用户名不能为空!";
                return result;
            }
            if (string.IsNullOrEmpty(userInfo.password) || userInfo.password == "******")
            {
                result.msg = "密码不能为空!";
                return result;
            }
            using (var context = DbUtils.Main.UseTransaction(true))
            {
                if (context.Sql("select count(*) from sysuser where loginname=@0", userInfo.username).QuerySingle<int>() > 0)
                {
                    result.ok = context.Sql("update sysuser set password=@0 where loginname=@1", MD5Helper.EnCode(userInfo.password).ToLower(), userInfo.username).Execute() > 0;
                }
                else
                {
                    result.ok = context.Sql("insert into sysuser(loginname,password) values(@0,@1)", userInfo.username, MD5Helper.EnCode(userInfo.password).ToLower()).Execute() > 0;
                }
                context.Commit();
            }
            return result;
        }

        public InvokeResult SaveConfigs(List<ConfigItem> configItems)
        {
            InvokeResult result = new InvokeResult();

            using (var context = DbUtils.Main.UseTransaction(true))
            {
                foreach (var item in configItems)
                {
                    if (context.Sql("select count(*) from sysconfig where ckey=@0", item.ckey).QuerySingle<int>() > 0)
                    {
                        context.Sql("update sysconfig set cvalue=@0 where ckey=@1", item.cvalue, item.ckey).Execute();
                    }
                    else
                    {
                        context.Sql("insert into sysconfig(ckey,cvalue) values(@0,@1)", item.ckey, item.cvalue).Execute();
                    }
                }
                context.Commit();
            }
            result.ok = true;
            return result;
        }

        public InvokeResult<List<ConfigItem>> LoadConfig()
        {
            InvokeResult<List<ConfigItem>> result = new InvokeResult<List<ConfigItem>>();
            result.data = DbUtils.Main.Sql("select ckey ,cvalue  from sysconfig").QueryMany<ConfigItem>();
            result.ok = true;
            return result;
        }

        public InvokeResult SaveConfigItem(ConfigItem configItem)
        {
            return SaveConfigs(new List<ConfigItem>() { configItem });
        }

        public InvokeResult<ConfigItem> GetConfigItem(string key)
        {
            InvokeResult<ConfigItem> result = new InvokeResult<ConfigItem>();
            result.data =
                DbUtils.Main.Sql("select ckey,cvalue from sysconfig where ckey=@0", key).QuerySingle<ConfigItem>();
            result.ok = result.data != null;
            return result;
        }

        public InvokeResult SavePhotoSize(PhotoSizeSubmitInfo photoSizeSubmitInfo)
        {
            InvokeResult result = new InvokeResult();

            using (var context = DbUtils.Main.UseTransaction(true))
            {

                if (context.Sql("select count(*) from photosize where name=@0", photoSizeSubmitInfo.name).QuerySingle<int>() > 0)
                {
                    context.Sql("update photosize set width=@0,height=@1 where name=@2", photoSizeSubmitInfo.width, photoSizeSubmitInfo.heigth, photoSizeSubmitInfo.name).Execute();
                }
                else
                {
                    context.Sql("insert into photosize(name,width,height) values(@0,@1,@2)", photoSizeSubmitInfo.name, photoSizeSubmitInfo.width, photoSizeSubmitInfo.heigth).Execute();
                }

                context.Commit();
            }
            result.ok = true;
            return result;
        }

        public InvokeResult<List<PhotoSizeInfo>> QueryPhotoSize()
        {
            InvokeResult<List<PhotoSizeInfo>> result = new InvokeResult<List<PhotoSizeInfo>>();
            result.data =
                DbUtils.Main.Sql("select picturetype,name,width,height from photosize order by width*height").QueryMany<PhotoSizeInfo>();
            result.ok = true;
            return result;
        }

        public InvokeResult CheckSalesmanExist(SalesmanInfo si)
        {
            InvokeResult result = new InvokeResult();
            result.ok = DbUtils.Main.Sql("select count(*) from salesman where SalesmanName=@0 and Id!=@1", si.SalesmanName, si.Id).QuerySingle<int>() > 0;
            return result;
        }

        public InvokeResult UpdateSalesmanInfo(SalesmanInfo si)
        {
            InvokeResult result = new InvokeResult();
            using (var context = DbUtils.Main.UseTransaction(true))
            {
                context.Update("salesman")
                    .Column("SalesmanName", si.SalesmanName)
                    .Column("Mobile", si.Mobile)
                    .Column("Address", si.Address)
                    .Where("Id", si.Id)
                    .Execute();

                context.Commit();
            }
            result.ok = true;

            return result;
        }

        public InvokeResult InsertSalesmanInfo(SalesmanInfo si)
        {
            InvokeResult result = new InvokeResult();
            using (var context = DbUtils.Main.UseTransaction(true))
            {
                context.Insert("salesman")
                    .Column("Id", si.Id)
                    .Column("SalesmanName", si.SalesmanName)
                    .Column("Mobile", si.Mobile)
                    .Column("Address", si.Address)
                    .Column("QrCodeUrl", si.QrCodeUrl)
                    .Column("CreateTime", si.CreateTime)
                    .Column("IsEnable", true)
                    .Execute();
                context.Commit();
            }
            result.ok = true;

            return result;
        }

        public InvokeResult<List<SalesmanInfo>> QuerySalesmanInfo()
        {
            InvokeResult<List<SalesmanInfo>> result = new InvokeResult<List<SalesmanInfo>>();
            result.data = DbUtils.Main.Sql(@"select a.Id,a.SalesmanName,a.Mobile,a.Address,a.QrCodeUrl,a.CreateTime,b.RecommendNum
                                                from salesman a
                                                LEFT JOIN
                                                (select SalesmanId,count(*) as RecommendNum from salesmanrecommend GROUP BY SalesmanId) b
                                                on a.Id=b.SalesmanId 
                                                ORDER BY a.CreateTime desc").QueryMany<SalesmanInfo>();
            result.ok = true;
            return result;
        }

        public InvokeResult<PageEntity<RecommendInfo>> QueryRecommendInfo(PageRequest pageRequest)
        {
            InvokeResult<PageEntity<RecommendInfo>> result = new InvokeResult<PageEntity<RecommendInfo>>();

            PageEntity<RecommendInfo> data = new PageEntity<RecommendInfo>();
            data.PageSize = pageRequest.pageSize;
            data.PageNo = pageRequest.pageNo;
            string whereStr = " 1=1 ";
            List<object> args = new List<object>();
            string order = pageRequest.order;
            if (string.IsNullOrEmpty(order))
                order = "a.createtime desc";
            pageRequest.conds = pageRequest.conds ?? "";
            var conds = pageRequest.conds.Split('|');
            foreach (var cond in conds)
            {
                if (cond.Split(':').Length != 2) continue;
                var key = cond.Split(':')[0];
                var val = cond.Split(':')[1];
                switch (key)
                {
                    case "mobile":
                        whereStr += " and b.Mobile=@" + args.Count;
                        args.Add(val);
                        break;
                    case "name":
                        whereStr += " and b.SalesmanName=@" + args.Count;
                        args.Add(val);
                        break;
                    case "bt":
                        whereStr += " and a.CreateTime>=@" + args.Count;
                        args.Add(val);
                        break;
                    case "et":
                        whereStr += " and a.CreateTime<=@" + args.Count;
                        args.Add(val);
                        break;
                }
            }


            data.RecordCount =
               DbUtils.Main.Sql("SELECT count(*) from salesmanrecommend a left join salesman b on a.SalesmanId=b.Id where " + whereStr, args.ToArray()).QuerySingle<int>();
            data.Records.AddRange(DbUtils.Main.Select<RecommendInfo>(@"a.OpenId,a.CreateTime,b.SalesmanName,b.Mobile,b.Address,b.IsEnable")
                                 .From(" salesmanrecommend a left join salesman b on a.SalesmanId=b.Id ")
                                 .Where(whereStr)
                                 .Paging(pageRequest.pageNo, pageRequest.pageSize)
                                 .Parameters(args.ToArray())
                                 .OrderBy(order)
                                 .QueryMany());
            result.data = data;
            result.ok = true;
            return result;
        }

        public InvokeResult<PageEntity<UnSubscribeInfo>> QueryUnSubscribeInfo(PageRequest pageRequest)
        {
            InvokeResult<PageEntity<UnSubscribeInfo>> result = new InvokeResult<PageEntity<UnSubscribeInfo>>();

            PageEntity<UnSubscribeInfo> data = new PageEntity<UnSubscribeInfo>();
            data.PageSize = pageRequest.pageSize;
            data.PageNo = pageRequest.pageNo;
            string whereStr = " 1=1 ";
            List<object> args = new List<object>();
            string order = pageRequest.order;
            if (string.IsNullOrEmpty(order))
                order = "createtime desc";
            pageRequest.conds = pageRequest.conds ?? "";
            var conds = pageRequest.conds.Split('|');
            foreach (var cond in conds)
            {
                if (cond.Split(':').Length != 2) continue;
                var key = cond.Split(':')[0];
                var val = cond.Split(':')[1];
                switch (key)
                {
                    case "openid":
                        whereStr += " and openid=@" + args.Count;
                        args.Add(val);
                        break;
                }
            }


            data.RecordCount =
               DbUtils.Main.Sql("SELECT count(*) from unsubscribelog where " + whereStr, args.ToArray()).QuerySingle<int>();
            data.Records.AddRange(DbUtils.Main.Select<UnSubscribeInfo>(@" OpenId,CreateTime ")
                                 .From(" unsubscribelog ")
                                 .Where(whereStr)
                                 .Paging(pageRequest.pageNo, pageRequest.pageSize)
                                 .Parameters(args.ToArray())
                                 .OrderBy(order)
                                 .QueryMany());
            result.data = data;
            result.ok = true;
            return result;
        }
    }
}